<?php

namespace common\models;

use Yii;
use yii\db\Query;

/**
 * This is the model class for table "project_update_log".
 *
 * @property string $id
 * @property string $project_id
 * @property string $module
 * @property integer $type
 * @property string $created_at
 * @property integer $user_id
 * @property string $log
 */
class ProjectUpdateLog extends \yii\db\ActiveRecord
{
    //操作类型
    const TYPE_MIXTURE = 1;//混合类
    const TYPE_PLEDGE = 2;//抵押类

    //公共模型
    const MODULE_BASE = 1;//基本信息
    const MODULE_LAWSUIT = 2;//涉诉信息
    const MODULE_TRANSFER = 3;//转让信息
    const MODULE_CONVERSION = 4;//流转、前期处置维护情况
    const MODULE_INVESTIGATION = 5;//债权基本情况
    const MODULE_BORROWER = 6;//借款人及资产情况
    const MODULE_PLEDGER = 7;//抵押人及抵押物情况
    const MODULE_WARRANTOR = 8;//保证人及资产情况
    const MODULE_OTHER = 9;//其他承债人及资产情况
    const MODULE_SUMMARIZE = 10;//尽调评估总结
    const MODULE_FILE = 11;//关键附件

    const MODULE_PERMISSION = 19;//访问权限
    const MODULE_JUDICIAL = 20;//司法进展

    //抵押类模型
    const MODULE_PLEDGER_RESERVATION = 12;//回现评估
    const MODULE_PLEDGER_SEIZE = 13;//抵押查封
    const MODULE_PLEDGER_VALUE_RESERVATION = 14;//抵押价值评估
    const MODULE_PLEDGER_NOT_VALUE_RESERVATION = 15;//非抵押价值评估
    const MODULE_PLEDGER_INTERVIEW = 16;//现场访谈
    const MODULE_PLEDGER_BASE = 21;//抵押物信息
    const MODULE_PLEDGER_PRICING_RESERVATION = 22;//定价评估
    const MODULE_PLEDGER_LIST =23; //抵押物列表

    //混合类模型
    const MODULE_VALUE_RESERVATION = 17;//价值评估
    const MODULE_ADDITIONAL_REMARKS = 18;//补充说明


    //混合类模块
    private $module_type1_title = array(
        self::MODULE_BASE => '基本情况',
        self::MODULE_LAWSUIT => '涉诉信息',
        self::MODULE_TRANSFER => '转让信息',
        self::MODULE_CONVERSION => '流转、前期处置维护情况',
        self::MODULE_INVESTIGATION => '债权基本情况',
        self::MODULE_BORROWER => '借款人及资产情况',
        self::MODULE_PLEDGER => '抵押人及抵押物情况',
        self::MODULE_WARRANTOR => '保证人及资产情况',
        self::MODULE_OTHER => '其他承债人及资产情况',
        self::MODULE_SUMMARIZE => '尽调评估总结',
        self::MODULE_FILE => '关键附件',

        self::MODULE_JUDICIAL =>'司法进展',
        self::MODULE_VALUE_RESERVATION => '价值评估',
        self::MODULE_ADDITIONAL_REMARKS => '补充说明',
        self::MODULE_PERMISSION => '访问权限',

    );


    //抵押类模块
    private $module_type2_title = array(
        self::MODULE_BASE => '基本情况',
        self::MODULE_LAWSUIT => '涉诉信息',
        self::MODULE_TRANSFER => '转让信息',
        self::MODULE_CONVERSION => '流转、前期处置维护情况',
        self::MODULE_INVESTIGATION => '债权基本情况',
        self::MODULE_BORROWER => '借款人及资产情况',
        self::MODULE_PLEDGER => '抵押人及抵押物情况',
        self::MODULE_WARRANTOR => '保证人及资产情况',
        self::MODULE_OTHER => '其他承债人及资产情况',
        self::MODULE_SUMMARIZE => '尽调评估总结',
        self::MODULE_FILE => '关键附件',

        self::MODULE_JUDICIAL =>'司法进展',
        self::MODULE_PLEDGER_RESERVATION => '回现评估',
        self::MODULE_PLEDGER_VALUE_RESERVATION => '抵押价值评估',
        self::MODULE_PLEDGER_NOT_VALUE_RESERVATION => '非抵押价值评估',
        self::MODULE_PLEDGER_LIST => '抵押物列表',
        self::MODULE_PLEDGER_SEIZE => '抵押查封',
        self::MODULE_PLEDGER_BASE => '抵押物信息',
        self::MODULE_PLEDGER_PRICING_RESERVATION => '定价评估',

        self::MODULE_PLEDGER_INTERVIEW => '现场访谈',
        self::MODULE_PERMISSION => '访问权限',

    );


    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'project_update_log';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['project_id', 'module'], 'required'],
            [['project_id', 'type', 'user_id'], 'integer'],
            [['created_at'], 'safe'],
            [['log'], 'string'],
            [['module'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'project_id' => '项目',
            'module' => '模块',
            'type' => '类型',
            'created_at' => '添加时间',
            'user_id' => '操作人',
            'log' => '操作内容',
        ];
    }

    /**
     * module类型组成的数组
     * @$type int 模块类型
     * @return array
    */
    public function getModuleArrayTitle($type = 1)
    {
        switch ($type) {
            case 1:
                return $this->module_type1_title;
                break;
            case 2:
                return $this->module_type2_title;
                break;
            default:
                return array();
        }
    }

    /**
     * 修改资产包用户
     * @return array  一维数组 用户id键，realname为值
     */
    public function getUsers()
    {
        $query = new Query();
        $users = $query->select(['p.user_id id', 'user.realname'])
            ->from(['p' => $this->tableName()])
            ->join('left join', 'user', 'user.id=p.user_id')
            ->groupBy('p.user_id')
            ->orderBy(['id' => SORT_ASC])
            ->all();

        if (empty($users)) {
            return array();
        }
        return yii\helpers\ArrayHelper::map($users, 'id', 'realname');
    }

    /**
     * 获取总条数
     * @param $projectId  项目id
     * @param $date  时间类型
     * @param $module 模型
     * @param $user 用户
     * @param $type module类型
     * @return int|string
     */
    public function getCount($projectId, $date, $module, $user, $type = 1)
    {
        $moduleArrayTitle = $this->getModuleArrayTitle($type);
        $oneWeekAgoDate = date("Y-m-d H:i:s", strtotime("-1 week"));    //一周前
        $oneMonthAgoDate = date("Y-m-d H:i:s", strtotime("-1 month"));    //一月前
        $currentDate = date('Y-m-d H:i:s', time());
        switch ($date) {
            //一周内
            case 1:
                $whereDate = ['and', ['between', 'created_at', $oneWeekAgoDate, $currentDate]];
                break;
            //一月内
            case 2:
                $whereDate = ['and', ['between', 'created_at', $oneMonthAgoDate, $currentDate]];
                break;
            //一月前
            case 3:
                $whereDate = ['and', ['<=', 'created_at', $oneMonthAgoDate]];
                break;
            //默认一月内
            default:
                $whereDate = ['and', ['between', 'created_at', $oneMonthAgoDate, $currentDate]];
        }

        $queryBulider = new yii\db\Query();
        $queryBulider
            ->select(['id', 'project_id', 'module', 'created_at', 'user_id', 'log'])
            ->from($this->tableName())
            ->where($whereDate);

        $whereType = ['and', 'type=' . $type];
        $queryBulider->andwhere($whereType);

        if ($user) {
            $whereUser = ['and', 'user_id=' . $user];
            $queryBulider->andwhere($whereUser);
        }

        if ($projectId) {
            $whereProjectId = ['and', 'project_id=' . $projectId];
            $queryBulider->andwhere($whereProjectId);
        }

        if ($module) {
            $whereModule = ['and', ['like', 'module', $moduleArrayTitle[$module]]];
            $queryBulider->andwhere($whereModule);
        }

        $count = $queryBulider->orderBy(['id' => SORT_DESC])
            ->indexBy('id')
            ->count();

        return $count;
    }

    /**
     * 获取列表
     * @param $date 时间类型
     * @param $projectId 项目id
     * @param $module 模型
     * @param $user 用户
     * @param $type module类型
     * @param int $limit 起始位置
     * @param int $offset 每页条数
     * @return array 二维
     */
    public function getList($projectId, $date, $module, $user, $type, $limit = 0, $offset = 20)
    {
        $moduleArrayTitle = $this->getModuleArrayTitle($type);
        $oneWeekAgoDate = date("Y-m-d H:i:s", strtotime("-1 week"));    //一周前
        $oneMonthAgoDate = date("Y-m-d H:i:s", strtotime("-1 month"));    //一月前
        $currentDate = date('Y-m-d H:i:s', time());
        switch ($date) {
            //一周内
            case 1:
                $whereDate = ['and', ['between', 'created_at', $oneWeekAgoDate, $currentDate]];
                break;
            //一月内
            case 2:
                $whereDate = ['and', ['between', 'created_at', $oneMonthAgoDate, $currentDate]];
                break;
            //一月前
            case 3:
                $whereDate = ['and', ['<=', 'created_at', $oneMonthAgoDate]];
                break;
            //默认一月内
            default:
                $whereDate = ['and', ['between', 'created_at', $oneMonthAgoDate, $currentDate]];
        }

        //$queryBulider = new yii\db\Query();
        //$sql = $queryBulider->select([])
        //    ->from('project_update_log')->
        //    Where($whereDate)
        //    ->offset($offset)->limit($limit)
        //    ->orderby(['id' => SORT_DESC])->createCommand()->getRawSql();
        // echo $sql;  exit();

        $queryBulider = new yii\db\Query();
        $queryBulider
            ->select(['id', 'project_id', 'module', 'created_at', 'user_id', 'log'])
            ->from($this->tableName())
            ->where($whereDate);

        $whereType = ['and', 'type=' . $type];
        $queryBulider->andwhere($whereType);

        if ($user) {
            $whereUser = ['and', 'user_id=' . $user];
            $queryBulider->andwhere($whereUser);
        }

        if ($projectId) {
            $whereProjectId = ['and', 'project_id=' . $projectId];
            $queryBulider->andwhere($whereProjectId);
        }

        if ($module) {
            $whereModule = ['and', ['like', 'module', $moduleArrayTitle[$module]]];
            $queryBulider->andwhere($whereModule);
        }

        $queryBulider->orderBy(['id' => SORT_DESC]);

        if ($limit == 0) {
            $queryBulider->limit($offset);
        } else {
            $queryBulider->limit($limit)->offset($offset);
        }

        $list = $queryBulider->indexBy('id')
            ->all();

        $userModel = new UserModel();
        $users = $userModel->getUsers();
        if (!empty($list) && is_array($list)) {
            foreach ($list as $key => $value) {
                $list[$key]['created_at'] = date('Y/m/d H:i:s', strtotime($value['created_at']));
                $list[$key]['user_id'] = $users[$value['user_id']];
                $list[$key]['log'] = $value['log'];

                $tmpStr = strip_tags($value['log']);
                $tmpLen = mb_strlen($tmpStr);
                $log = mb_substr($tmpStr, 0, 35, 'utf-8') . (($tmpLen > 35) ? '...' : '');
                $list[$key]['log2'] = $log;
            }
            return $list;
        }

        return array();
    }

}
